"""
scons build file

EPAPI

@author: Jean-Lou Dupont
"""
import os
import shutil
from string import Template

from helpers import *

Help("""\
   'scons' to build the libraries (release and debug),
   'scons deb' to build the .deb package
   'scons docs' to build the documentation
   'scons rel' to release the package to tags/debian repository
   'scons install' to install on local machine
   'scons installlib' to install the libraries on local machine
""")

# LIST MODULES
# ============
includes = ['#lib/include',]

list_modules = [	'#lib',
					'#test/echo',
				]

# HEADER files
# ============
headers = ['%s.h', '%s_msg.h', '%s_pkt.h']

modules = []
for module in list_modules:
	modules.append( {	'script'  : "%s/SConscript" % module,
						'build'   : module,
						'release' : Environment(CPPPATH=[module+'/include']+includes),
						'debug'   : Environment(CPPPATH=[module+'/include']+includes, CPPFLAGS="-D_DEBUG -g", _DEBUG='1')
					} )

for module in modules:
	SConscript(module['script'], build_dir=module['build']+'/release', exports={'env':module['release']})
	SConscript(module['script'], build_dir=module['build']+'/debug',   exports={'env':module['debug']})


this_lib = "epapi"
env=Environment()

#========================================================


def read_version():
	file = open('./VERSION')
	version = file.read()
	file.close()
	return version

def replace_params(path_src, path_dest, params):
	"""
	Replace the parameters in the target path
	"""
	file = open(path_src,"r")
	contents = file.read()
	file.close()
	
	tpl=Template(contents)
	updated_content = tpl.safe_substitute( **params )
	
	file = open(path_dest, "w")
	file.write(updated_content)
	file.close()
	
	
def adjust_control_files(params, c_path):
	"""
	Replace the $version parameter in the control files
	"""
	files = ['control', 'postinst', 'postrm', 'preinst', 'prerm']
	for file in files:
		path = "%s/%s" % (c_path, file)
		print "scons: adjusting [%s]" % path
		replace_params(path,path,params)

def get_gcpwd():
	path = os.path.expanduser("~")
	file = open("%s/.gcpwd" % path)
	pwd = file.read().strip()
	file.close()
	return pwd

def get_gcuser():
	path = os.path.expanduser("~")
	file = open("%s/.gcuser" % path)
	user = file.read().strip()
	file.close()
	return user


# BUILDING .deb PACKAGE
# =====================
if 'deb' in COMMAND_LINE_TARGETS:
	print "Preparing .deb package"
	try:
		version = read_version()
		print """scons: building release [%s]""" % version
		
		print """scons: cloning release library""" 
		shutil.copy('./lib/release/lib%s.so' % this_lib, "./packages/debian/usr/lib/lib%s-%s.so" % (this_lib,version) )
		
		print """scons: cloning debug library"""
		shutil.copy('./lib/debug/lib%s_debug.so' % this_lib, './packages/debian/usr/lib/lib%s_debug-%s.so' % (this_lib,version) )
		
		print """scons: cloning header file(s) & adjusting version"""
		for hdr in headers:
			frag =  hdr % this_lib
			spath = "./lib/include/%s" % frag
			dpath = "./packages/debian/usr/include/%s" % frag
			shutil.copy(spath, dpath)
			replace_params(dpath, dpath, {'version':version} )
		
		print """scons: removing directory"""
		shutil.rmtree('/tmp/%s_deb' % this_lib, ignore_errors=True)

		#print """scons: updating debian 'control' with version[%s]""" % version
		#generate_control(version)
		
		print """scons: cloning ./packages/debian to /tmp directory"""
		safe_copytree('./packages/debian', '/tmp/%s_deb' % this_lib, skip_dirs=['.svn',], dir_mode=0775, make_dirs=True)

		print """scons: adjusting version in control files"""
		c_path = '/tmp/%s_deb/DEBIAN' % this_lib
		params = {'version':version}
		adjust_control_files(params, c_path)
		

		#print """scons: cloning 'Packages.gz'"""
		#shutil.copy("../dists/stable/main/binary-i386/Packages.gz", "/tmp/%s_deb/Packages.gz" % this_lib)
		
		print """scons: adjusting permissions for `dkpg-deb` command-line"""
		recursive_chmod("/tmp/%s_deb" % this_lib, mode=0775)


	except Exception,e:
		print "*** ERROR [%s] ***" % e
	
env.Command("deb", "/tmp/%s_deb" % this_lib, "dpkg-deb --build $SOURCE")

	

# RELEASING
#
#  The 'deb' command is assumed to have been performed.
#  The 'deb' package is assumed to be sitting in /tmp
#
# =========
if 'rel' in COMMAND_LINE_TARGETS:

	# extract "version"
	version = read_version()
	print "scons: RELEASING version %s" % version
	
	name = "%s_%s-1_i386.deb" % (this_lib,version)
	path = "/tmp/%s" % name
	print "scons: renaming debian package: %s" % name
	shutil.copy('/tmp/%s_deb.deb' % this_lib, path)

	print "scons: copying [%s] to repo in dists/main/binary-i386" % path
	shutil.copy(path, "../../dists/stable/main/binary-i386")
	
	debian_path = "../../dists/stable/main/binary-i386/%s" % name
	print "scons: running dpkg-scanpackages  [%s]" % debian_path
	os.system("cd ../.. && dpkg-scanpackages -m dists/stable/main/binary-i386 /dev/null | gzip -9c > dists/stable/main/binary-i386/Packages.gz")
	
	print "scons: removing archive build directory"
	try:    shutil.rmtree("/tmp/%s/%s" % (this_lib, this_lib))
	except: pass
	
	print "scons: creating sources archive"
	safe_copytree('./lib', '/tmp/%s/%s' % (this_lib,this_lib), skip_dirs=['.svn', 'debug', 'release'], dir_mode=0775, make_dirs=True)
	os.system("rm /tmp/%s/%s/.sconsign.dblite" % (this_lib, this_lib))
	os.system("rm /tmp/%s/%s/SConscript" % (this_lib,this_lib))
	os.system("cd /tmp/%s && zip -r /tmp/%s-sources-%s.zip %s -x *.svn* *.os *.so" % (this_lib, this_lib, version, this_lib))
	
	
if 'up' in COMMAND_LINE_TARGETS:
	import gcupload as gc
	
	version = read_version()

	print "scons: uploading to Google Code"
	user= get_gcuser()
	pwd =  get_gcpwd()
	
	#upload(file, project_name, user_name, password, summary, labels=None)
	src = "/tmp/%s-sources-%s.zip" % (this_lib, version)
	gc.upload(src, this_lib, user, pwd, "sources archive", ["sources", "featured"])
	
	deb = "/tmp/%s_%s-1_i386.deb" % (this_lib, version)
	gc.upload(deb, this_lib, user, pwd, "debian binary-i386", ["Type-Package", "OpSys-Linux", "featured"])
		
	
# DOCS
# ====
if 'docs' in COMMAND_LINE_TARGETS:
	print "scons: generating docs"
	os.system("doxygen")
	
	path = "./docs/html/index.html"
	version = read_version()
		
	print "scons: adjusting $version [%s] in html docs [%s]" % (version, path)
	
	replace_params( path, path, {'version':version})

